package com.channel.temperature.collect.app.util

import android.content.Context
import android.provider.Settings
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.channel.temperature.collect.app.api.NetUrl
import com.channel.temperature.collect.app.ext.mmkv
import com.channel.temperature.collect.data.annotation.ValueKey
import com.channel.temperature.collect.data.response.ApiResponseTwo
import com.channel.temperature.collect.data.response.DataBean
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import me.hgj.mvvmhelper.base.appContext
import rxhttp.toAwait
import rxhttp.wrapper.param.RxHttp
import java.security.KeyFactory
import java.security.spec.X509EncodedKeySpec
import java.util.Base64

class MyWorker(context: Context, params: WorkerParameters) : Worker(context, params) {
    override fun doWork(): Result {
        uploadLog()

        return Result.success()
    }

    public fun uploadLog() {
        CoroutineScope(Dispatchers.Default).launch {
            if (NetCheckUtils.isNetworkAvailable()) {

                var location = mmkv.getString(ValueKey.APP_LOCATION_KEY, "")
                // 执行任务逻辑
                var encodeString = RSAUtils.encryptByPublicKey(
                    getAndroidId(), KeyFactory.getInstance("RSA").generatePublic(
                        X509EncodedKeySpec(
                            Base64.getDecoder().decode(RSAUtils.publicKeyString)
                        )
                    )
                )
                var dataBean = RxHttp.get(NetUrl.BASE_URL + "/index/appdevices/add_log")
                    .add("mData", encodeString)
                    .add("longx", if (location.isNullOrEmpty()) "" else location.split("_")[0])
                    .add("lat", if (location.isNullOrEmpty()) "" else location.split("_")[1])
                    .toAwait<ApiResponseTwo<DataBean>>()
                    .await()
//            Log.e("测试", "执行任务返回结果 " + dataBean.code + "  " + dataBean.info)
            }
        }

    }

    private fun getAndroidId(): String {
        var uniqueID = Settings.Secure.getString(
            appContext.contentResolver, Settings.Secure.ANDROID_ID
        )
        return uniqueID
    }
}
